package org.zuel.boot.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.zuel.boot.demo.web.*;
import org.zuel.boot.demo.exception.ParameterException;
import org.zuel.boot.demo.entity.SysUser;
import org.zuel.boot.demo.mapper.SysUserMapper;
import org.zuel.boot.demo.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.util.Arrays;


/**
 *  服务实现类
 *
 * @author ikun
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public PageResult<SysUser> list(PageParam<SysUser> page) {
        return new PageResult<>(this.page(page).getRecords(), page.getTotal());
    }

    @Override
    public JsonResult read(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        SysUser sysUser = baseMapper.selectById(id);
        return JsonResult.ok().setData(sysUser);
    }

    @Override
    public JsonResult add(SysUser sysUser) {
        if (sysUser ==null){
            throw new ParameterException("参数对象为空");
        }

        baseMapper.insert(sysUser);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult update(SysUser sysUser) {
        if (sysUser == null) {
            throw new ParameterException("参数对象为空");
        }

        if (sysUser.getUserId() == null) {
            throw new ParameterException("参数对象id为空");
        }

        baseMapper.updateById(sysUser);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null) {
            throw new ParameterException("参数对象为空");
        }

        if (ids != null || ids.length > 0) {
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }

    @Override
    public JsonResult login(SysUser sysUser) {
        // 查询用户
        SysUser user = baseMapper.selectOne(new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()));

        // 验证用户是否存在
        if (user == null) {
            return JsonResult.error("用户不存在");
        }

        // 验证密码是否正确
        if (!user.getPassword().equals(sysUser.getPassword())) {
            return JsonResult.error("Invalid password");
        }

        // 登录成功
        return JsonResult.ok("登录成功");
    }

}